package com.xunk.scene.util;

import cn.hutool.core.util.IdUtil;
import com.xunk.common.core.utils.StringUtils;
import com.xunk.common.redis.service.RedisService;
import com.xunk.scene.constant.SceneConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * @ProjectName: HIM
 * @Package: com.xunk.scene.util
 * @ClassName: RedisUtil
 * @Author: tangguangyuan
 * @Description:场景 缓存值操作类，启动时将场景密钥存入redis ，获取redis
 * @Date: 2021/5/15 10:38
 * @Version: 1.0
 */

@Component
public class RedisUtil implements ApplicationRunner {
    private static final Logger log = LoggerFactory.getLogger(RedisUtil.class);

    @Autowired
    RedisService redisService;


    //供其他方法获取场景密钥
    public String getKey() {
        String key;
        key = redisService.getCacheObject(SceneConstant.SCENE_KEY);
        if (StringUtils.isEmpty(key)) {
            log.info(String.format("无法获取到场景密钥: %s，设置新的密钥"));
            redisService.setCacheObject(SceneConstant.SCENE_KEY, IdUtil.randomUUID());
            log.info(String.format("场景密钥设置完成：%s", SceneConstant.SCENE_KEY));
            key = redisService.getCacheObject(SceneConstant.SCENE_KEY);
        }
        return key;
    }

    //项目启动时初始化场景密钥
    @Override
    public void run(ApplicationArguments args) {

        //随机生成密钥存入redis
        String sceneKey = IdUtil.randomUUID();
        redisService.setCacheObject(SceneConstant.SCENE_KEY, sceneKey);
        log.info(String.format("场景密钥设置完成：%s", SceneConstant.SCENE_KEY));


        /*//启动时将城市代码存入redis

        List<Region> regionList = regionMapper.queryAllRegion();
        redisService.*/
    }

}
